<?php 
class deptClassAction extends ActionManage
{
	public function defaultAction()
	{
		
	}
	
	private function pensegsetx($rows, $pid, $level)
	{
		$len = 0;
		foreach($rows as $k=>$rs){
			if($rs['pid']==$pid){
				$rs['level'] = $level;
				$this->tempdata[] = $rs;
				$zlen1= count($this->tempdata)-1;
				$zlen = $this->pensegsetx($rows, $rs['id'], $level+1);
				$this->tempdata[$zlen1]['stotal'] = $zlen;
				$len++;
			}
		}
		return $len;
	}
	
	public function dataAction()
	{
		$rows = m('dept')->getall('1=1','*','sort asc');
		$this->tempdata = array();
		$this->pensegsetx($rows, 0, 1);
		return array(
			'rows' => $this->tempdata,
			'success'=> true
		);
	}
	
	public function formAction()
	{
		$id = (int)$this->get('id','0');
		$this->smartydata['id'] = $id;
		$rs['name'] = '';
		$rs['num'] = '';
		$rs['headman'] = '';
		$rs['headid'] = '';
		$rs['sort'] = '0';
		$rs['pid'] = (int)$this->get('pid','0');;
		if($id>0){
			$rs = m('dept')->getone('`id`='.$id.'');
		}
		$this->smartydata['rs'] = $rs;
	}
	
	public function savecheckAction()
	{
		$name = $this->post('name');
		$num = $this->post('num');
		$id = (int)$this->post('id','0');
		$pid = (int)$this->post('pid','0');
		if($id==0 && $pid==0)return '上级ID不能为0';

		$uarr= array(
			'name' 	=> $name,
			'num' 	=> $num,
			'num' 	=> $num,
			'pid' 	=> $pid,
			'headman' 	=> $this->post('headman'),
			'headid' 	=> $this->post('headid'),
			'sort' 	=> (int)$this->post('sort'),
		);
		$where = '`id`='.$id.'';
		if($id==0){
			
			$where = '';
		}
		$bo 	= m('dept')->record($uarr, $where);
		if(!$bo)return $this->db->error();
		
		return 'ok';
	}
	
}